package com.meirengu.channel.service.impl;

import com.meirengu.channel.service.CcicService;
import com.meirengu.utils.XMLParser;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwCcicPush;
import com.meirengu.webview.model.KwCcicPushLog;
import com.meirengu.webview.service.KwCcicPushLogService;
import com.meirengu.webview.service.KwCcicPushService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;

/**
 * 大地保险
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class CcicServiceImpl implements CcicService {

    Logger logger = LoggerFactory.getLogger(CcicServiceImpl.class);

    @Autowired
    private KwCcicPushService kwCcicPushService;
    @Autowired
    private KwCcicPushLogService kwCcicPushLogService;

    /**
     * @param
     * @return
     */

    public Integer applyLoan(String name, String mobile, String gender, int age,
                             String birthDate, String createdDate, String occupation,
                             String salary, String salaryType, int mortgageTab,
                             int houseFundTab, int insuranceTab, int autoLoanTab,
                             int socialSecurityTab, int houseTab, int autoTab,
                             int creditTab, String loan, String provinceId) throws Exception {

        String url = ConfigUtil.getConfig("ccic.url");

        //组装数据
        String xmlInfo = getXmlInfo(name, mobile, gender, age, birthDate,
                createdDate, occupation, salary, salaryType, mortgageTab,
                houseFundTab, insuranceTab, autoLoanTab, socialSecurityTab, houseTab,
                autoTab, creditTab, loan, provinceId);


        //接口调用信息表
        KwCcicPush kwCcicPush = new KwCcicPush();
        kwCcicPush.setInterfaceCode("ccic");
        kwCcicPush.setInterfaceName("大地保险");
        kwCcicPush.setMobile(mobile);
        kwCcicPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwCcicPushLog kwCcicPushLog = new KwCcicPushLog();
        kwCcicPushLog.setInterfaceCode("ccic");
        kwCcicPushLog.setInterfaceName("大地保险");
        kwCcicPushLog.setMobile(mobile);
        kwCcicPushLog.setSendUrl(url.toString());
        kwCcicPushLog.setParams(xmlInfo);


        String hr = null;
        try {
            hr = sendPost(url, xmlInfo);
            /*int code = hr.getStatusCode();
            if(code == 200){*/
            kwCcicPushLog.setBackUrl(hr);
            kwCcicPushLog.setHttpCode(200);
            kwCcicPushLog.setHttpContent(hr);

            logger.info("==CcicServiceImpl.applyLoan request success. result:{}", hr.toString());

            Map<String, Object> map = XMLParser.getMapFromXML(hr);
            String rCode = map.get("DatabusStatus").toString();
            String rMsg = map.get("errorMessage").toString();
            String Customer_Guid = map.get("Customer_Guid").toString();
            if ("0000".equals(rCode)) {
                kwCcicPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                kwCcicPush.setMessage(Customer_Guid);
                logger.info("==CcicServiceImpl.applyLoan business success");
            } else {
                kwCcicPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                kwCcicPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                logger.warn("==CcicServiceImpl.applyLoan business fail");
            }
            /*}else {
                thirdback.setBackUrl(hr.toString());
                thirdback.setHttpCode(code);
                thirdback.setHttpContent(hr.toString());
                logger.warn("==CcicServiceImpl.applyLoan request fail. code:{}, result:{}", code, hr.toString());
            }*/
        } catch (Exception e) {
            kwCcicPushLog.setHttpCode(408);
            kwCcicPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwCcicPushService.insert(kwCcicPush);
            kwCcicPushLog.setPushId(kwCcicPush.getId());
            kwCcicPushLogService.insert(kwCcicPushLog);
            return kwCcicPush.getCode();
        }
    }


    private String sendPost(String u, String sendxml) throws Exception {
        /*String u="https://ywtest.ccic-net.com.cn:8912/MicrofGeneral/PerSonLoan";*/
        /*System.setProperty("javax.net.ssl.trustStore", "/Users/lx/Desktop/test2.jks");*/
        System.setProperty("javax.net.ssl.trustStore", "/Users/lx/Desktop/ccic/ccic.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "123456");
        System.setProperty("javax.net.ssl.keyStoreType", "JKS");
        /*System.setProperty("javax.net.ssl.keyStore","/Users/lx/Desktop/test2.jks") ;*/
        System.setProperty("javax.net.ssl.keyStore", "/Users/lx/Desktop/ccic/ccic.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "123456");
         /*   System.getProperties().put("proxySet", "true");
		 	System.getProperties().put("proxyHost", "10.1.27.102");
		 	System.getProperties().put("proxyPort", "8080");*/

        URL url = new URL(u);
        HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
        http.setDoOutput(true);
        http.setDoInput(true);
        http.setRequestProperty("Content-Type", "text/xml;charset=gbk");
        http.setRequestMethod("POST");
        OutputStreamWriter out = new
                OutputStreamWriter(http.getOutputStream(), "GBK");
        String xmlInfo = sendxml;
        out.write(xmlInfo);
        out.flush();
        out.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(http
                .getInputStream()));
        String line = "";
        StringBuffer sb = new StringBuffer();
        for (line = br.readLine(); line != null; line = br.readLine()) {
            sb.append(line);
        }
        return sb.toString();

    }

    private String getXmlInfo(String name, String mobile, String gender, int age,
                              String birthDate, String createdDate, String occupation,
                              String salary, String salaryType, int mortgageTab,
                              int houseFundTab, int insuranceTab, int autoLoanTab,
                              int socialSecurityTab, int houseTab, int autoTab,
                              int creditTab, String loan, String provinceId) throws Exception {
        //测试报文，换成你们自己的。
        /*String name = URLEncoder.encode("张三三","gbk");*/
        /*String name = "张三三";
        String mobile = "15835132986";
        *//*String gender = URLEncoder.encode("男","gbk");*//*
        String gender = "男";
        int age = 28;
        String birthDate = "1990-06-05";
        String createdDate = "2018-03-27";
        *//*String occupation = URLEncoder.encode("公务员","gbk");*//*
        String occupation = "公务员";
        String salary = "10000";
        *//*String salaryType = URLEncoder.encode("打卡","gbk");*//*
        String salaryType = "打卡";
        int mortgageTab = 1;
        int houseFundTab = 1;
        int insuranceTab = 1;
        int autoLoanTab = 1;
        int socialSecurityTab = 1;
        int houseTab = 1;
        int autoTab = 1;
        int creditTab = 1;
        String loan = "100000";
        String provinceId = "C00050";*/

        String huanya =

                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                        "<root>\n" +
                        "<SourceCode>LADL</SourceCode>\n" +
                        "<Base>\n" +
                        "<Customer_Guid></Customer_Guid>\n" +
                        "<CreatedDate>" + createdDate + "</CreatedDate>\n" +
                        "<BusinessChannel></BusinessChannel>\n" +
                        "<MedieCode></MedieCode>\n" +
                        "</Base>\n" +
                        "<Personal>\n" +
                        "<CustomerName>" + name + "</CustomerName>\n" +
                        "<Mobile>" + mobile + "</Mobile>\n" +
                        "<Gender>" + gender + "</Gender>\n" +
                        "<Age>" + age + "</Age>\n" +
                        "<BirthDate>" + birthDate + "</BirthDate>\n" +
                        "<Email></Email>\n" +
                        "<Assets></Assets>\n" +
                        "<CreatedDate>" + createdDate + "</CreatedDate>\n" +
                        "<Terminal>M</Terminal>\n" +
                        "</Personal>\n" +
                        "<AssetInformation>\n" +
                        "<Occupation>" + occupation + "</Occupation>\n" +
                        "<Salary>" + salary + "</Salary>\n" +
                        "<SalaryType>" + salaryType + "</SalaryType>\n" +
                        "<Borrow_Tab></Borrow_Tab>\n" +
                        "<Mortgage_Tab>" + mortgageTab + "</Mortgage_Tab>\n" +
                        "<HouseFund_Tab>" + houseFundTab + "</HouseFund_Tab>\n" +
                        "<Insurance_Tab>" + insuranceTab + "</Insurance_Tab>\n" +
                        "<AutoLoan_Tab>" + autoLoanTab + "</AutoLoan_Tab>\n" +
                        "<SocialSecurity_Tab>" + socialSecurityTab + "</SocialSecurity_Tab>\n" +
                        "<House_Tab>" + houseTab + "</House_Tab>\n" +
                        "<Auto_Tab>" + autoTab + "</Auto_Tab>\n" +
                        "<Credit_Tab>" + creditTab + "</Credit_Tab>\n" +
                        "<Loan>" + loan + "</Loan >\n" +
                        "<TimeLimit></TimeLimit>\n" +
                        "<ProductType></ProductType>\n" +
                        "<OrderStatus></OrderStatus>\n" +
                        "<HighQualityOrder></HighQualityOrder>\n" +
                        "</AssetInformation>\n" +
                        "<AddressList>\n" +
                        "<Province_id>" + provinceId + "</Province_id>\n" +
                        "<City_id></City_id>\n" +
                        "<Address></Address>\n" +
                        "</AddressList>\n" +
                        "</root>";


        StringBuffer sb = new StringBuffer();
        sb.append(huanya);
        return sb.toString();
    }


}
